import { ref, onMounted, onUnmounted } from 'vue';

export function useCaptchaCountdown(initialTime = 60) {
  const countdown = ref(initialTime);
  let timer: any = null;

  // 倒计时函数
  const startCountdown = (fn: any) => {
    if (countdown.value !== initialTime) return;
    countdown.value--;
    fn?.();
    clearInterval(timer);
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        stopCountdown();
      }
    }, 1000);
  };

  // 停止倒计时
  const stopCountdown = () => {
    clearInterval(timer);
    countdown.value = initialTime; // 重置倒计时
  };

  // 在组件卸载时停止倒计时
  onUnmounted(() => {
    stopCountdown();
  });

  // 暴露给外部的 ref 和方法
  return {
    countdown,
    disabled: computed(() => {
      return countdown.value !== initialTime;
    }),
    text: computed(() => {
      if (countdown.value !== initialTime) {
        return `${countdown.value}s`;
      }
      return '发送验证码';
    }),
    startCountdown, // 如果你需要在组件外部手动开始倒计时，可以暴露这个方法
    stopCountdown, // 如果你需要在组件外部手动停止倒计时，可以暴露这个方法
  };
}
